package utils;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Environment;
import android.os.Handler;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

import common.Constant;
import https.UpLoadFileController;
import topic.adapter.DeliverCommentGridViewAdapter;

/**
 * Created by Administrator on 2017/3/13.、
 *  图片处理
 */

public class BitmapUtils {

    private static final String TAG = "BitmapUtils";

    //根据指定的bitmap路径加载，并定义好了目标的大小
    public static void decodeFile(final String path, final DeliverCommentGridViewAdapter.LoadLocalImg loadLocalImg, final int dstWidth, final int dstHeight) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                BitmapFactory.Options options = new BitmapFactory.Options();
                options.inJustDecodeBounds = true;
                BitmapFactory.decodeFile(path, options);
                options.inJustDecodeBounds = false;
                options.inSampleSize = calculateSampleSize(options.outWidth, options.outHeight, dstWidth, dstHeight);
                Bitmap unscaledBitmap = BitmapFactory.decodeFile(path, options);
                if (unscaledBitmap != null) {
                    unscaledBitmap = createScaledBitmap(unscaledBitmap, dstWidth, dstHeight);
                }
                loadLocalImg.loadLocalImg(unscaledBitmap);
//                unscaledBitmap.recycle();
            }
        }).start();
    }

    /**
     * 获得经过处理的bitmap
     */
    public static Bitmap createScaledBitmap(Bitmap unscaledBitmap, int dstWidth, int dstHeight) {

        Rect srcRect = calculateSrcRect(unscaledBitmap.getWidth(), unscaledBitmap.getHeight(),
                dstWidth, dstHeight);
        Rect dstRect = calculateDstRect(unscaledBitmap.getWidth(), unscaledBitmap.getHeight(),
                dstWidth, dstHeight);
        Bitmap scaledBitmap = Bitmap.createBitmap(dstRect.width(), dstRect.height(),
                Bitmap.Config.RGB_565);
        Canvas canvas = new Canvas(scaledBitmap);
        canvas.drawBitmap(unscaledBitmap, srcRect, dstRect, new Paint(Paint.FILTER_BITMAP_FLAG));
        return scaledBitmap;
    }

    /**
     * 计算Option的inSampleSize属性
     */
    private static int calculateSampleSize(int srcWidth, int srcHeight, int dstWidth, int dstHeight) {
        final float srcAspect = (float) srcWidth / (float) srcHeight;
        final float dstAspect = (float) dstWidth / (float) dstHeight;
        if (srcAspect > dstAspect) {
            return srcWidth / dstWidth;
        } else {
            return srcHeight / dstHeight;
        }
    }

    /**
     * 计算源文件的Rect
     */
    private static Rect calculateSrcRect(int srcWidth, int srcHeight, int dstWidth, int dstHeight) {
        return new Rect(0, 0, srcWidth, srcHeight);
    }

    /**
     * 计算目标bitmap的rect区域
     */
    private static Rect calculateDstRect(int srcWidth, int srcHeight, int dstWidth, int dstHeight) {
        float factor;
        if (srcWidth > dstWidth && srcHeight > dstHeight) {
            //当原图大于缩略图时
            if (srcHeight > srcWidth) {
                //如果原图高大于宽
                factor = (float) srcWidth / (float) dstWidth;
                int newHeight = (int) Math.ceil(srcHeight / factor);
                int newCenter = (dstHeight / 2) - 90;
                return new Rect(0, newCenter, dstWidth, newHeight);
            } else {
                factor = (float) srcHeight / (float) dstHeight;
                int newWidth = (int) Math.ceil(srcWidth / factor);
                int newCenter = (dstWidth / 2) - 90;
                return new Rect(newCenter, 0, newWidth, dstHeight);
            }
        } else {
            return new Rect(0, 0, dstWidth, dstHeight);
        }
    }


    public static void saveBitmapFile(final String path, DeliverCommentGridViewAdapter.LocalImgComplete localimgComplete, final String name) {
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeFile(path, options);
        options.inJustDecodeBounds = false;
        options.inSampleSize = calculateSampleSize(options.outWidth, options.outHeight, 800, 800);
        Bitmap bitmap = BitmapFactory.decodeFile(path, options);

        if (bitmap != null) {
            File dir = new File(Constant.PICTURE_DIR);//将要保存图片的路径
            if (!dir.exists()) {
                dir.mkdirs();
            }
            File file = new File(dir.getPath() + "/" + name+ ".jpg");//将要保存图片的路径
            if (file.exists()) {
                file.delete();
            }
            try {
                ByteArrayOutputStream bao = new ByteArrayOutputStream();
                bitmap.compress(Bitmap.CompressFormat.JPEG, 100, bao);
                int quality = 100;
                while (bao.toByteArray().length / 1024 > 100) {    // 循环判断如果压缩后图片是否大于100kb,大于继续压缩
                    if (quality >= 10) {
                        bao.reset();// 重置baos即清空baos
                        quality -= 10;// 每次都减少10
                        bitmap.compress(Bitmap.CompressFormat.JPEG, quality, bao);// 这里压缩options%，把压缩后的数据存放到baos中
                    }
                }
                ByteArrayInputStream isBm = new ByteArrayInputStream(bao.toByteArray());
                Bitmap img = BitmapFactory.decodeStream(isBm, null, null);
                try {
                    FileOutputStream out = new FileOutputStream(file);
                    img.compress(Bitmap.CompressFormat.JPEG, 100, out);
                    out.flush();
                    out.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
                isBm.close();
                bao.flush();
                bao.close();
                localimgComplete.localImgComplete(file);
                if(bitmap != null && !bitmap.isRecycled()){
                    // 回收并且置为null
                    bitmap.recycle();
                }
                if(img != null && !img.isRecycled()){
                    // 回收并且置为null
                    img.recycle();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    // 上传图片
    public static void upLoadIma(Context context, Handler handler, File file) {
        if (file.exists()) {
            new UpLoadFileController(context, Constant.UPLOADIMAGE, handler, null, file, 0);
        }
    }

    //删除本地存的图片
    public static void deleteBitmapFile(String name) {
        File dir = new File(Constant.PICTURE_DIR);//将要保存图片的路径
        if (!dir.exists()) {
            dir.mkdirs();
        }
        File file = new File(dir.getPath() + "/" + name + ".jpg");//将要保存图片的路径
        if (file.exists()) {
            file.delete();
        }else{
            MyLogUtils.e(TAG,file.getPath());
        }
    }

    public static boolean isBitmapExists(String path) {
        File file = new File(path);
        MyLogUtils.e(TAG, file.length() + "");
        if( file.length()>0){
            //判断是否有该图片
            return true;
        }
        return false;
    }


    //缓存图片回收
    public static void recycleBitmap(Drawable drawable){
            if (drawable != null && drawable instanceof BitmapDrawable) {
                BitmapDrawable bitmapDrawable = (BitmapDrawable) drawable;
                Bitmap bitmap = bitmapDrawable.getBitmap();
                if (bitmap != null && !bitmap.isRecycled()) {
                    bitmap.recycle();
                    System.gc();
                }
            }
    }
}
